﻿using SharedLib.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Tracy.DataModel.Config;

namespace Tracy.BasicServices
{
    public class TracyConfigurationManager
    {
        private XmlDocument _doc;
        private XmlElement _rootNode;

        private string FileName
        {
            get { return AppDataHelper.GetAppDataFile("Configuration.xml"); }
        }

        private List<IConfigurable> _managedItems;

        public List<IConfigurable> ManagedItems
        {
            get
            {
                if (_managedItems == null) _managedItems = new List<IConfigurable>();
                return _managedItems;
            }
        }

        public TracyConfigurationManager()
        {
            _doc = new XmlDocument();
            if (File.Exists(FileName))
            {
                _doc.Load(FileName);
                _rootNode = _doc.SelectSingleNode("/configuration") as XmlElement;
            }

            if (_rootNode == null)
            {
                _rootNode = _doc.CreateElement("configuration");
                _doc.AppendChild(_rootNode);
            }
        }

        public void Attach(IConfigurable item)
        {
            XmlElement configNode = _rootNode.SelectSingleNode("config[@name='" + item.Name + "']") as XmlElement;
            if (configNode != null)
            {
                item.LoadConfig(configNode);
            }
            if (!ManagedItems.Contains(item)) ManagedItems.Add(item);
        }

        public void Update(IConfigurable item, IConfigModel configModel)
        {
            if (item != null)
            {
                XmlElement configNode = _rootNode.SelectSingleNode("config[@name='" + item.Name + "']") as XmlElement;
                if (configNode != null)
                {
                    _rootNode.RemoveChild(configNode);
                }
                if (configModel != null)
                {
                    (_rootNode.AppendChild(configModel.ToXmlNode(_doc)) as XmlElement).SetAttribute("name", item.Name);
                }
                _doc.Save(FileName);
            }
        }
    }
}
